import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:ball_lion/module/match/detail/zq_match_detail_logic.dart';
import 'package:ball_lion/module/live/live_chat_logic.dart';
import 'package:ball_lion/entity/match/match_live_entity.dart';
import 'package:ball_lion/utils/ali_message.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/module/match_detail/live/match_live_view.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'package:ball_lion/server/api/other_api.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/module/match_detail/live/live_source_sheet.dart';
import 'package:ball_lion/server/api/live_api.dart';
import 'package:ball_lion/module/match/detail/lq_match_detail_logic.dart';
import 'package:ball_lion/widgets/player/qs_player_logic.dart';

class AliLiveLogic extends GetxController {
  late QsPlayerLogic? playerLogic;
  GlobalKey viewKey = GlobalKey();
  late int sportsId;
  int? _viewId;
  MatchLiveEntity? roomInfo;
  int? roomId;
  String? _matchInfo;
  List<MatchLiveEntity>? liveList;
  AppLifecycleListener? _lifecycleListener;
  bool hasAnimate = false;

  String? get matchInfo => _matchInfo;
  int? get viewId => _viewId;

  set viewId(int? value) {
    _viewId = value;
    update();
  }

  set matchInfo(String? value) {
    _matchInfo = value;
    update();
  }

  @override
  void onReady() {
    if (roomInfo?.vtype == 2) {
      playerLogic?.setLoop(true);
    }
    _lifecycleListener =
        AppLifecycleListener(onDetach: () => LiveApi.closeLiveRoom(roomId));
    const MethodChannel('mainInit').setMethodCallHandler((call) {
      if (call.method == 'shutdown') {
        LiveApi.closeLiveRoom(roomId);
      }
      return Future.value(null);
    });
    getLiveList();
    super.onReady();
  }

  @override
  void onClose() {
    LiveApi.closeLiveRoom(roomId);
    _lifecycleListener?.dispose();
    super.onClose();
  }

  Future getLiveList() async {
    final result =
        await OtherApi.getVideoList(roomInfo?.matchId ?? 0, sportsId, null);
    if (result != null) {
      liveList = result.where((element) => element.vtype != 4).toList();
      hasAnimate = result.any((element) => element.vtype == 4);
    }
    update();
  }

  void changeOrientation() async {
    if (Get.mediaQuery.orientation == Orientation.landscape) {
      Utils.onEvent("liveroom_landsacpe_swith", params: {"landscape": 0});
      await SystemChrome.setPreferredOrientations(
          [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
      await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
      await Future.delayed(const Duration(microseconds: 500))
          .then((value) async {
        Get.back();
        await Future.delayed(const Duration(milliseconds: 100));
        try {
          // await playerLogic?.setPlayerView(playerLogic!.currentViewId!);
          playerLogic?.doRefresh();
        } catch (e) {
          Logger().d(e);
        }
      });
      return;
    } else {
      Utils.onEvent("liveroom_landsacpe_swith", params: {"landscape": 1});
      SystemChrome.setPreferredOrientations(
          [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
      await Future.delayed(const Duration(milliseconds: 300));
      await Get.to(MatchLiveView(liveInfo: roomInfo, sportsId: sportsId));
      return;
    }
  }

  void back() async {
    if (MediaQuery.of(Get.context!).orientation == Orientation.landscape) {
      await SystemChrome.setPreferredOrientations(
          [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
      await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
      await Future.delayed(const Duration(microseconds: 500))
          .then((value) async {
        Get.back();
        await Future.delayed(const Duration(milliseconds: 100));
        try {
          // await playerLogic?.setPlayerView(playerLogic!.currentViewId!);
          playerLogic?.doRefresh();
        } catch (e) {
          Logger().d(e);
        }
      });
    } else {
      Get.back();
    }
  }

  Future changeLive() async {
    await getLiveList();
    final index = await LiveSourceSheet.show(
        liveList: liveList ?? [],
        select: roomInfo?.expertId ?? "",
        isFullScreen:
            MediaQuery.of(Get.context!).orientation == Orientation.landscape);
    if (index == null) return;
    AliMessage().leaveGroup(roomInfo?.chatGroupId ?? "", roomInfo?.roomId);
    if (liveList?[index].vtype != 4 &&
        (!(liveList?[index].playStatus.hasValue ?? false))) {
      Toast.text("暂未开始直播，请耐心等待");
      return;
    }
    if (liveList?[index].vformat == 'URL') {
      launchUrlString(liveList?[index].url ?? '',
          mode: LaunchMode.externalApplication,
          webViewConfiguration:
              const WebViewConfiguration(enableDomStorage: false));
    } else {
      if (liveList?[index].copyright == 0) {
        if (liveList?[index].url != roomInfo?.url) {
          try {
            if (sportsId == 1) {
              Get.find<ZqMatchDetailLogic>(tag: "${roomInfo?.matchId}")
                  .setLiveStream(true, roomInfo: liveList?[index]);
            } else {
              Get.find<LqMatchDetailLogic>(tag: "${roomInfo?.matchId}")
                  .setLiveStream(true, roomInfo: liveList?[index]);
            }
            if (liveList?[index].chatGroupId.hasValue ?? false) {
              AliMessage().enterGroup(liveList?[index].chatGroupId ?? "");
            }
          } catch (e) {
            log("");
          }
          doRefresh(info: liveList?[index]);
        }
      } else {
        Toast.text('暂无版权，请选择其他直播源');
      }
    }
    roomInfo = liveList?[index];
    update();
  }

  void dismiss() {
    playerLogic?.player.destroy();
    if (sportsId == 1) {
      try {
        Get.find<ZqMatchDetailLogic>(tag: "${roomInfo?.matchId}")
            .setLiveStream(false);
      } catch (e) {
        log(e.toString());
      }
    } else {
      try {
        Get.find<LqMatchDetailLogic>(tag: "${roomInfo?.matchId}")
            .setLiveStream(false);
      } catch (e) {
        log(e.toString());
      }
    }
  }

  void doRefresh({MatchLiveEntity? info}) {
    if (info?.vtype == 0) {
      try {
        LiveChatLogic chatLogic = Get.find<LiveChatLogic>(
            tag: "${info?.matchId ?? roomInfo?.matchId}");
        chatLogic.getRefresh();
      } catch (e) {
        log("");
      }
    }
    try {
      playerLogic?.url = info?.url ?? roomInfo?.url ?? "";
      playerLogic?.doRefresh();
    } catch (e) {
      log("");
    }
    update();
  }

  void changeToAnimate() {
    if (sportsId == 1) {
      ZqMatchDetailLogic logic =
          Get.find<ZqMatchDetailLogic>(tag: "${roomInfo?.matchId}");
      logic.onTapLive(false);
    } else {
      LqMatchDetailLogic logic =
          Get.find<LqMatchDetailLogic>(tag: "${roomInfo?.matchId}");
      logic.onTapLive(false);
    }
  }
}
